package com.pay.merchant.controller;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pay.constant.Constant;
import com.pay.entity.Merchant;
import com.pay.jwt.JWT;
import com.pay.merchant.mapping.MappingUtils;
import com.pay.service.IBaseInfoService;
import com.pay.service.IMerchantService;
import com.pay.utils.Login;
import com.pay.utils.ResponseData;
import com.pay.utils.TokenUtils;

import cn.hutool.core.util.StrUtil;

/**
 * 基础controlle
 * @author Administrator
 *
 */
@Controller
public class BaseController {

	@Autowired
	private IBaseInfoService baseInfoService ;
	
	@Autowired
	private IMerchantService merchantService ;
	
	@RequestMapping(value=MappingUtils.login)
	public ModelAndView login() {
		String siteName = baseInfoService.getByKey(Constant.siteName);
		String vaptchaVID = baseInfoService.getByKey(Constant.merchantVaptchaVID);
		ModelAndView m = new ModelAndView(MappingUtils.login);
		m.addObject("siteName", siteName + "商户后台登录") ;
		m.addObject("vaptchaVID", vaptchaVID) ;
		return m ;
	}
	
	@RequestMapping(value=MappingUtils.root)
	public void root(HttpServletResponse response,HttpServletRequest request) throws IOException {
		Integer loginId = null ;
		String token = TokenUtils.getMerchantToken(request) ;
		if(StrUtil.isNotBlank(token)) {
			Login login = JWT.unsign(token, Login.class);
			if(login != null) {
				loginId = login.getId() ;
			}
		}
		response.sendRedirect(MappingUtils.index + "?loginId=" + (loginId == null ? "" : loginId)) ;	
	}
	
	
	@ResponseBody
	@RequestMapping(value=MappingUtils.enter,method= {RequestMethod.POST})
	public ResponseData enter(Login login,HttpServletRequest request) {
		login.setIp(request.getRemoteAddr());
		ResponseData responseData = ResponseData.ok() ;
		
		Merchant merchant = merchantService.checkLogin(login) ;
		if(merchant != null) {
			login.setId(merchant.getId());
			//给用户jwt加密生成token 有效期60分钟
            String token = JWT.sign(login, TimeUnit.MINUTES.toMillis(60));
            //封装成对象返回给客户端
            responseData.putDataValue("loginId", login.getId());
            responseData.putDataValue("token", token);
            responseData.putDataValue("user", merchant);
            responseData.putDataValue("tokentime", TimeUnit.MINUTES.toMillis(60));
		}else {
			responseData =  ResponseData.baseError("用户名密码错误");
		}
		
		return responseData ;
	}
}
